<?php
// 应用公共文件

function sm4_cbc_encrypt($plain, $key)
{
    $command = "echo {$plain}  | /opt/tongsuo/bin/tongsuo enc -K  {$key} -e -sm4-cbc -iv  1fb2d42fb36e2e88a220b04f2e49aa13 -nosalt -base64";
    return shell($command);
}


function sm4_cbc_decrypt($plain, $key)
{
    $command = "echo {$plain}  | /opt/tongsuo/bin/tongsuo enc -K  {$key} -d -sm4-cbc -iv  1fb2d42fb36e2e88a220b04f2e49aa13 -nosalt -base64";
    return shell($command);
}

function sm3_dgst($str)
{
    $command = "echo -n {$str} | /opt/tongsuo/bin/tongsuo dgst -sm3";
    return shell($command);
}


function sm2_verify($sigFile, $file)
{
    $pubKey = key_path() . '/sm2pub.key';
    $file = upload_path() . ltrim($file, '.');
    $sigFile = upload_path() . ltrim($sigFile, '.');
    $command = "/opt/tongsuo/bin/tongsuo dgst -sm3 -verify {$pubKey} -signature {$sigFile} {$file}";
    return shell($command);
}

function sm2_sign($sigFile, $file)
{
    $key = key_path() . '/sm2.key';
    $file = upload_path() . ltrim($file, '.');
    $sigFile = upload_path() . ltrim($sigFile, '.');
    $command = "/opt/tongsuo/bin/tongsuo dgst -sm3 -sign {$key} -out {$sigFile} {$file}";
    return shell($command);
}


function shell($command)
{
    exec($command, $output, $return_var);

    $output_str = implode("\n", $output);
    $error_str = '';

    if ($return_var !== 0) {
        $error_str = "Error executing command: $command\n";
    }

    $result = array('output' => $output_str, 'error' => $error_str);
    return $result;
}

function key_path()
{
    $dir = dirname(dirname(base_path()));
    $dir = str_replace('\\', '/', $dir);
    return $dir;
}

function upload_path()
{
    $dir = dirname(base_path());
    $dir = str_replace('\\', '/', $dir);
    return $dir;
}


function send_file($file_path, $as_attachment = true)
{
    // Set headers for download
    if ($as_attachment) {
        header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
    }
    header('Content-Type: ' . mime_content_type($file_path));
    header('Content-Length: ' . filesize($file_path));

    // Read file and output to browser
    readfile($file_path);
}






